package artem;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends Thread {
	private ServerSocket socketFactory;

	public static void main(String[] args) {
		Server server = new Server();
		server.start();
	}

	public void run() {
		try {
			socketFactory = new ServerSocket(7777);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try (BufferedOutputStream fileOut = new BufferedOutputStream(
				new FileOutputStream("data\\dst3.bin"))) {
			System.out.println("Waiting for a connection.");

			Socket socket = socketFactory.accept();

			System.out.println("Connection accepted.");

			InputStream in1 = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			out.flush();
			byte[] buffer = new byte[100000];
			int size;
			int sum = 0;

			int totalSize = 0;

			while ((size = in1.read(buffer)) != -1) {
//				totalSize += size;

//				System.out.println("Progress: " + totalSize + "b.");

				fileOut.write(buffer, 0, size);
				if ((sum += size) >= 104857600) {
					break;
				}
			}
			out.write(1);
			out.flush();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
